
package com.gitlab.bootren.aliyun.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.internal.Mimetypes;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * @author serv
 */
public class FileClientServiceImpl implements FileClientService {


    private FileClientSettings clientSettings;

    private OSSClient _client;

    public FileClientServiceImpl(FileClientSettings clientSettings) {
        this.clientSettings = clientSettings;
    }

    private OSSClient getClient() {
        if(_client==null){
            _client =  new OSSClient(clientSettings.getEndpoint(), clientSettings.getAccessKeyId(), clientSettings.getAccessKeySecret(), clientSettings);
        }
        return _client;

    }


    @Override
    public FileResult saveFile(byte[] data, String key, ObjectMetadata metadata) throws Exception {

        if(StringUtils.isEmpty(key)){
            throw new RuntimeException("filename不能为空");
        }
        if(key.startsWith("/")){
            key = key.substring(1,key.length());
        }
        if(metadata==null){
            metadata = new ObjectMetadata();
        }

        if(data!=null&&data.length>0){
            metadata.setContentLength(data.length);
        }
        if(StringUtils.isEmpty(metadata.getContentType())){
            metadata.setContentType(Mimetypes.getInstance().getMimetype(key));
        }

        ByteArrayInputStream inputStream = new ByteArrayInputStream(data);

        PutObjectResult result = getClient().putObject(clientSettings.getBucket(), key, inputStream, metadata);

        FileResult fileResult = new FileResult();
        fileResult.setBucket(clientSettings.getBucket());
        fileResult.setProtocol(clientSettings.getProtocol().name().toLowerCase());
        fileResult.setEndpoint(clientSettings.getEndpoint());
        fileResult.setEtag(result.getETag());
        fileResult.setKey(key);
        fileResult.setUrl(getUrl(key));
        return fileResult;
    }



    @Override
    public FileResult saveFile(InputStream data, String key, long length) throws Exception {
        if(StringUtils.isEmpty(key)){
            throw new RuntimeException("filename不能为空");
        }
        if(key.startsWith("/")){
            key = key.substring(1,key.length());
        }
        ObjectMetadata  metadata = new ObjectMetadata();
        metadata.setContentLength(length);
        if(StringUtils.isEmpty(metadata.getContentType())){
            metadata.setContentType(Mimetypes.getInstance().getMimetype(key));
        }

        PutObjectResult result = getClient().putObject(clientSettings.getBucket(), key, data, metadata);

        FileResult fileResult = new FileResult();
        fileResult.setBucket(clientSettings.getBucket());
        fileResult.setProtocol(clientSettings.getProtocol().name().toLowerCase());
        fileResult.setEndpoint(clientSettings.getEndpoint());
        fileResult.setEtag(result.getETag());
        fileResult.setKey(key);
        fileResult.setUrl(getUrl(key));
        return fileResult;
    }

    @Override
    public FileResult saveFile(byte[] data, String key) throws Exception {
        return this.saveFile(data,key,null);
    }

    @Override
    public FileResult saveFile(File file) throws Exception {
        return this.saveFile(file,null);
    }

    @Override
    public FileResult saveFile(File file, ObjectMetadata metadata) throws Exception{
        return this.saveFile(Files.readAllBytes(file.toPath()),file.getPath(),metadata);
    }

    public ObjectListing listFiles(String prefix) throws Exception{
        if(prefix.startsWith("/")){
            prefix = prefix.substring(1,prefix.length());
        }
        if(!prefix.endsWith("/")){
            prefix += "/";
        }
        return this.getClient().listObjects(clientSettings.getBucket(),prefix);
    }

    @Override
    public String getUrl(String key) {
        try {
            //如果在图片服务需要的扩展名列表内，则返回图片服务域名
            if(clientSettings.getExtensions().contains(FilenameUtils.getExtension(key))){
                return clientSettings.getProtocol().name().toLowerCase()+"://"+clientSettings.getImgDomain()+"/"+key;
            }else{
                return clientSettings.getProtocol().name().toLowerCase()+"://"+clientSettings.getFileDomain()+"/"+key;
            }
        }catch (Exception e){
            return clientSettings.getProtocol().name().toLowerCase()+"://"+clientSettings.getBucket()+"."+clientSettings.getEndpoint()+"/"+key;
        }

    }
}
